package com.example.covid.Utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录检查 拦截器
 * 1.配置好拦截器要拦截那些请求
 * 2.把这些配置放在容器中
 * @author KamenRider
 */
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

  /**
   * 目标方法执行之前
   * @param request
   * @param response
   * @param handler
   * @return
   * @throws Exception
   */
  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
      throws Exception {
    // 获取session 判断session用户信息是否存在
    Object userInfo = request.getSession().getAttribute("userInfo");
    if (userInfo == null) {
      // 未登录
      log.debug("未登录请求:" + request.getRequestURI());
      response.sendRedirect("/login");
      return false;
    }
    log.debug("放行请求:" + request.getRequestURI());
    return true;
  }

}
